import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:test_app/core/design_system/extensions/extensions.dart';

import 'form_modal.dart';

/// switch组件（从 BaseForm 中拆分出来的独立部件）。
///
/// 保留原有的校验逻辑：
/// - 如果 require == true，则为空时提示「{label}不能为空」
/// 开关
Widget buildSwitchField({
  required FormModal item,
  required GlobalKey<FormBuilderFieldState> fieldKey,
  Widget Function(Widget label, Widget field)? containerBuilder,
}) {
  final defaultValidator = FormBuilderValidators.compose([
    FormBuilderValidators.required(errorText: '${item.label}不能为空'),
  ]);

  return FormBuilderField<bool>(
    name: item.field,
    key: fieldKey,
    validator: item.validator ?? ((item.require ?? false) ? defaultValidator : null),
    builder: (fieldState) {

      final tdSwitch = Align(
        alignment: Alignment.centerRight,
        child: TDSwitch(
          isOn: fieldState.value ?? false,
          onChanged: (value) {
            fieldState.didChange(value);
            return value;
          },
        ),
      );

      final labelWidget = Text(item.label);
      final fieldWidget = Expanded(child: tdSwitch);

      final row = item.containerBuilder != null
          ? item.containerBuilder!(labelWidget, fieldWidget)
          : containerBuilder != null
          ? containerBuilder(labelWidget, fieldWidget)
          : [labelWidget, fieldWidget]
          .toRow()
          .padHorizontal(16)
          .height(58)
          .backgroundColor(const Color(0xFFFFFFFF))
          .clipRadius(8);

      return row;

    },
  );
}
